import React from 'react';
// import isDev from 'isdev';
import { renderToString } from 'react-dom/server';
import { match, RouterContext,createRoutes } from 'react-router';
import routesApp from '../../src/router';
// import routesApp from '../../dist/ssr/ssr';

import {Provider} from 'mobx-react';
// import {fetchData} from '../../src/utils/fetch'

import {dehydrate} from '../../src/state/hydrate'

import {fetchData} from '../../src/stores/storeInServer'

// import initStore from '../../src/stores'
const routesC = createRoutes(routesApp());

var html;

function handleRouter(res, props) {

  // console.log('props: ', props);

  // console.log('handleRouter: ');

  fetchData(props.location).then(data=>{

    html = renderToString(<RouterContext {...props} />);

    res
      .status(200)
      .render('index', {
          root: html,
          state:JSON.stringify(data)
      });

  })
  //  const html = '<h1>test</h1>';

//   const store = initStore({
//       app:{ssrLocation:req.url}
//   })
  
  
  
}

function handleRedirect(res, redirect) {
  res.redirect(302, redirect.pathname + redirect.search);
}

function handleNotFound(res) {
  res.status(404).send('Not Found');
}

function handleError(res, err) {
  res.status(500).send(err.message);
}

export function isoMiddleware(req, res) {
  console.log('req.url: ', req.url);
  match({ routes:routesC, location: req.url },
    (err, redirect, props) => {
      if (err) handleError(res, err);
      else if (redirect) handleRedirect(res, redirect);
      else if (props) handleRouter(res, props);
      else handleNotFound(res);
    });
}
